package com.wangsd.web.sys.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wangsd.common.basicbean.Result;
import com.wangsd.web.MyController;
import com.wangsd.web.sys.entity.SysUser;
import com.wangsd.web.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.wangsd.common.enums.CommonStatic.LOGIN_TOKEN_TYPE_W;
import static com.wangsd.common.enums.ResultCode.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author generator
 * @since 2019-09-02
 */
@Api(value = "sysUser", tags = "用户管理")
@RestController
@RequestMapping("/sys/sysUser")
@Slf4j
public class SysUserController extends MyController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    SysUserService sysUserService;

    @ApiOperation(value = "查询用户列表", notes = "查询用户列表", httpMethod = "POST")
    @RequestMapping(value = "/selectList/{pageNum}/{pageSize}", method = RequestMethod.POST)
    public Result selectList(@ApiParam(value = "当前页", required = true) @PathVariable("pageNum") Integer pageNum,
                             @ApiParam(value = "每页大小", required = true) @PathVariable("pageSize") Integer pageSize,
                             @RequestBody @ApiParam(name = "user", value = "传入json格式") SysUser user) {


        SysUser userInfo = getUserInfo();
        String code = null;
        if (user.getType() == null) {
            user.setType(userInfo.getType());
        }

        /*非超级管理员，需要使用code查找当前用户所能看到的数据*/
        if (userInfo.getType() != 99) {
            code = userInfo.getCode();
        }

        IPage<SysUser> sysUserIPage = sysUserService.selectList(code, pageNum, pageSize, user);

        return Result.success(sysUserIPage);
    }


    @ApiOperation(value = "新增或修改用户信息", notes = "新增或修改用户信息", httpMethod = "POST", response = Result.class)
    @RequestMapping(value = "addOrUpdate", method = RequestMethod.POST)
    public Result addOrUpdate(@RequestBody SysUser user) {

        SysUser old = sysUserService.selectByUsernameOrId(user.getUsername(), user.getId());
        if (old != null) {
            return Result.message(NAME_REPEAT);
        }
        Integer integer = sysUserService.addOrUpdate(user);

        return Result.success(integer);
    }


    @ApiOperation(value = "删除用户信息", notes = "删除用户信息", httpMethod = "GET", response = Result.class)
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public Result delete(@ApiParam(value = "用户id", required = true) @PathVariable("id") Long id) {

        boolean b = sysUserService.removeById(id);

        return Result.success(b);
    }

    @ApiOperation(value = "通过id查询用户信息", notes = "通过id查询用户信息", httpMethod = "GET", response = Result.class)
    @GetMapping("/selectById/{id}")
    public Result selectById(@ApiParam(value = "用户id", required = true) @PathVariable Long id) {

        SysUser user = sysUserService.getById(id);

        return Result.success(user);
    }

    @ApiOperation(value = "用户登录", notes = "用户登录", httpMethod = "POST", response = Result.class)
    @PostMapping("/login")
    public Result login(@ApiParam(value = "用户名", required = true) @RequestParam("username") String username,
                        @ApiParam(value = "密码", required = true) @RequestParam("password") String password) {

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return new Result(ACCOUNT_PASSWORD_ERROR);
        }
        SysUser user = sysUserService.selectLogin(username, password);
        if (user != null) {
            String token = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(LOGIN_TOKEN_TYPE_W+token, user, 12, TimeUnit.HOURS);
            Map<String, String> map = new HashMap<>();
            map.put("token", LOGIN_TOKEN_TYPE_W+token);
            return Result.success(map);
        }
        return new Result(ACCOUNT_PASSWORD_ERROR);

    }

    @ApiOperation(value = "用户登出", notes = "用户登出", httpMethod = "GET", response = Result.class)
    @RequestMapping("/logout")
    public Result logout() {
        String token = request.getHeader("Access-Token");
        if (token != null) {
            redisTemplate.delete(token);
        }
        return Result.success();
    }

    @ApiOperation(value = "获取登录用户详情", notes = "获取登录用户详情", httpMethod = "GET", response = Result.class)
    @GetMapping("/getUserInfo")
    public Result getUserAndRole() {
        SysUser loginUser = getUserInfo();
        loginUser = sysUserService.getById(loginUser.getId());
        loginUser = sysUserService.selectPermission(loginUser);
        return Result.success(loginUser);
    }

    @ApiOperation(value = "修改用户密码", notes = "修改用户密码", httpMethod = "POST", response = Result.class)
    @RequestMapping(value = "updatePassword", method = RequestMethod.POST)
    public Result updatePassword(@RequestBody SysUser user) {
        SysUser userInfo = getUserInfo();
        SysUser old = sysUserService.selectByUsernameOrId(user.getUsername(), userInfo.getId());
        if (old != null) {
            return Result.message(NAME_REPEAT);
        }
        user.setId(userInfo.getId());
        boolean b = sysUserService.updateById(user);
        return Result.success(b);
    }

    /*******************************以下是示例***********************************/
    /*@ApiOperation(value = "保存测试用例Demo", notes = "保存测试用例Demo", httpMethod = "POST", response = Result.class)
     *//*用于覆盖掉SysUser中的参数验证*//*
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名称", dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", paramType = "form")
    })
    @RequestMapping(value = "saveDemo", method = RequestMethod.POST)
    public Result saveDemo(SysUser sysUser) {
        *//*需要对保存的参数进行验证*//*
        boolean b = sysUserService.save(sysUser);

        return Result.success(b);
    }


    @ApiOperation(value = "新增或修改用户信息Demo", notes = "新增或修改用户信息Demo", httpMethod = "POST", response = Result.class)
    @RequestMapping(value = "saveOrUpdateDemo", method = RequestMethod.POST)
    public Result saveOrUpdateDemo(SysUser user) {

        boolean b = sysUserService.saveOrUpdate(user);
        log.debug("保存返回主键id = {}", user.getId());
        return Result.success(b);
    }

    @ApiOperation(value = "查询用户列表Demo", notes = "查询用户列表Demo", httpMethod = "POST")
    @RequestMapping(value = "/selectListDemo/{pageNum}/{pageSize}", method = RequestMethod.POST)
    public Result<List<SysUser>> selectListDemo(@ApiParam(value = "当前页", required = true) @PathVariable("pageNum") Integer pageNum,
                                            @ApiParam(value = "每页大小", required = true) @PathVariable("pageSize") Integer pageSize,
                                            @RequestBody @ApiParam(name = "user", value = "传入json格式") SysUser user) {

        IPage<SysUser> sysUserIPage = sysUserService.selectListDemo(pageNum, pageSize, user);

        return Result.success(sysUserIPage);
    }*/
    /*******************************以下是示例***********************************/
}

